import { GridContent } from '@ant-design/pro-layout';
import React, { forwardRef, useState, useEffect } from 'react';
import { Input, Form, Select, Modal } from 'antd';
import CodeMirrorShell from '@/pages/global/codeMirrorShell';
// import { parse } from 'qs';
const { Option } = Select;
const { TextArea } = Input;

// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/ban-types
const Step: React.ForwardRefExoticComponent<
  React.PropsWithoutRef<{
    getForm: Function;
    open: boolean;
    onCancel: Function;
    onOk: Function;
    modelData?: PRO.step;
  }> &
    React.RefAttributes<unknown>
> = forwardRef(
  (props: {
    getForm: Function;
    open: boolean;
    onCancel: Function;
    onOk: Function;
    modelData?: PRO.step;
  }) => {
    const [form] = Form.useForm();
    const [showImage, setShowImage] = useState(false);
    const [showCode, setShowCode] = useState(false);

    const getRandomString = (len: number) => {
      const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';
      // eslint-disable-next-line prefer-const
      let min = 0,
        max = _charStr.length - 1,
        _str = '';
      //判断是否指定长度，否则默认长度为15
      // eslint-disable-next-line no-param-reassign
      len = len || 15;
      //循环生成字符串
      for (let i = 0, index; i < len; i++) {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        index = RandomIndex(min, max, i);
        _str += _charStr[index];
      }
      return _str;
    };
    const RandomIndex = (min: number, max: number, i: number) => {
      const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';
      let index = Math.floor(Math.random() * (max - min + 1) + min),
        // eslint-disable-next-line prefer-const
        numStart = _charStr.length - 10;
      //如果字符串第一位是数字，则递归重新获取
      if (i == 0 && index >= numStart) {
        index = RandomIndex(min, max, i);
      }
      //返回最终索引值
      return index;
    };
    useEffect(() => {
      form.setFieldsValue(props.modelData);
      if (props.modelData && props.modelData.run_type == 1) {
        setShowImage(true);
      } else {
        //不暂时docker容器选择配置
        setShowImage(false);
      }
    }, [form, props.modelData, props.open]);
    const GetFormData = async () => {
      return new Promise((resolve, reject) => {
        form
          .validateFields()
          .then(() => {
            const data = form.getFieldsValue();
            if (!data.unique_id) {
              data.unique_id = getRandomString(15);
            }
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    };

    const runStep = [
      {
        key: 0,
        value: '在宿主机执行',
      },
      {
        key: 1,
        value: '在容器内运行',
      },
    ];
    // @ts-ignore
    const getHtml = () => {
      if (showImage) {
        return (
          <Form.Item
            label="docker镜像"
            name="docker_image"
            rules={[
              {
                required: true,
                message: '请输入需要运行的容器镜像!',
              },
            ]}
          >
            <Input />
          </Form.Item>
        );
      }
    };
    // eslint-disable-next-line @typescript-eslint/no-shadow
    // // eslint-disable-next-line @typescript-eslint/no-unused-vars
    // const params: any = parse(window.location.search, { ignoreQueryPrefix: true });
    //
    // // eslint-disable-next-line @typescript-eslint/no-unused-vars
    // @ts-ignore
    // @ts-ignore
    // @ts-ignore
    // @ts-ignore
    // @ts-ignore

    // @ts-ignore
    return (
      <GridContent>
        <CodeMirrorShell
          open={showCode}
          defaultValue={props.modelData?.step_template}
          onOk={() => {
            setShowCode(false);
          }}
          onchange={(code: any) => {
            console.log(code.doc.getValue());
            form.setFieldValue('step_template', code.doc.getValue());
          }}
          okCancel={() => {
            setShowCode(false);
          }}
        />
        <Modal
          forceRender={true}
          onCancel={() => {
            props.onCancel();
          }}
          open={props.open}
          onOk={() => {
            GetFormData()
              .then((data: any) => {
                props.onOk(data, form);
              })
              .catch((err) => {
                console.log(err);
              });
          }}
        >
          <Form
            form={form}
            name="basic"
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 16,
            }}
            initialValues={props.modelData}
            // onFinish={async (values) => {
            //   await handleSubmit(values as PRO.Project);
            // }}
            // onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="步骤名称"
              name="step_name"
              rules={[
                {
                  required: true,
                  message: '请输入步骤名称!',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              hidden={true}
              label="id"
              name="id"
              rules={[
                {
                  required: false,
                  message: '请输入步骤名称!',
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="执行模式"
              name="run_type"
              rules={[
                {
                  required: true,
                  message: '请选择执行模式!',
                },
              ]}
            >
              <Select
                value="0"
                onChange={(value) => {
                  if (value == '1') {
                    setShowImage(true);
                  } else {
                    setShowImage(false);
                  }
                }}
              >
                {runStep.map((item) => {
                  // eslint-disable-next-line react/jsx-key
                  return (
                    <Option value={item.key} key={item.key}>
                      {item.value}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            {getHtml()}
            <Form.Item
              label="执行的命令"
              name="step_template"
              tooltip="模板{{}}模板写法"
              rules={[
                {
                  required: true,
                  message: '需要执行的命令!',
                },
              ]}
            >
              <TextArea
                onClick={() => {
                  setShowCode(true);
                }}
                rows={6}
              />
            </Form.Item>

            <Form.Item
              label="参数json"
              name="template_args"
              tooltip="参数会替换模板中的定义的模板"
              rules={[
                {
                  required: false,
                  message: '命令中的参数json!',
                },
              ]}
            >
              <TextArea rows={4} />
            </Form.Item>

            <Form.Item
              label="额外参数"
              name="ext_params"
              tooltip="--buildTimeout=number/s 设置构建流程的过期时间"
              rules={[
                {
                  required: false,
                  message: '命令中的参数json!',
                },
              ]}
            >
              <TextArea rows={4} />
            </Form.Item>

            <Form.Item
              hidden={true}
              label="unique_id"
              name="unique_id"
              tooltip="参数会替换模板中的定义的模板"
              rules={[
                {
                  required: false,
                  message: '命令中的参数json!',
                },
              ]}
            >
              <Input />
            </Form.Item>
          </Form>
        </Modal>
      </GridContent>
    );
  },
);

// @ts-ignore
export default Step;
